package service

import (
	"team-evaluate/global"
	"team-evaluate/internal/model"
	"team-evaluate/pkg/errcode"
)

func (svc *Service) CreateTeam(param *model.CreateTeamRequest) error {
	// 先判断改用户是否创建过同名的团队
	list, err := svc.dao.FindTeamByName(param.CreatedBy, param.Name)
	if err != nil {
		return err
	}
	if len(list) > 0 {
		return errcode.ErrorTeamNameDuplicate
	}
	return svc.dao.CreateTeam(param.Name, param.CreatedBy, param.Desc)
}

func (svc *Service) CountTeam() (int64, error) {
	return svc.dao.CountTeam()
}

func (svc *Service) FindTeamById(param *model.FindByIdTeamRequest) (*model.TeamRes, error) {
	return svc.dao.FindTeamById(param.ID)
}

func (svc *Service) FindTeamByName(param *model.FindByNameTeamRequest) ([]*model.TeamRes, error) {
	return svc.dao.FindTeamByName(param.CreatedBy, param.Name)
}

func (svc *Service) GetTeamList(param *model.ListTeamRequest) (int, []*model.TeamRes, *errcode.Error) {
	totalRows, err := svc.dao.MyCountTeam(param.CreatedBy)
	if err != nil {
		global.Logger.Errorf("svc.MyCountTeam err: %v", err)
		return 0, nil, errcode.ErrorCountTeamFail.WithDetails(err.Error())
	}
	teams, err := svc.dao.GetTeamList(param.CreatedBy, param.Pager.Page, param.Pager.PageSize)
	if err != nil {
		global.Logger.Errorf("svc.GetTeamList err: %v", err)
		return 0, nil, errcode.ErrorGetListListFail.WithDetails(err.Error())
	}
	return int(totalRows), teams, nil
}

func (svc *Service) UpdateTeam(param *model.UpdateTeamRequest) error {
	// 先判断改用户是否创建过同名的团队
	list, err := svc.dao.FindTeamByName(param.CreatedBy, param.Name)
	if err != nil {
		return err
	}
	if len(list) > 0 {
		return errcode.ErrorTeamNameDuplicate
	}
	return svc.dao.UpdateTeam(param.ID, param.Name, param.Desc)
}

func (svc *Service) DeleteTeam(param *model.DeleteTeamRequest) error {
	return svc.dao.DeleteTeam(param.ID)
}
